<?php

namespace Admin\Controller;

class HospitalOrderController extends AdminbaseController {

    function _initialize() {
        parent::_initialize();
        $this->currentModel = D("HospitalOrder");
    }

    //首页
    public function index() {

        $requestMap = $this->convertRequestToMap();
        $requestMap["ho#status-neq"] = -2;
//        if(!isNullOrEmpty($requestMap["ho#create_date-elt"])){
//            $requestMap["ho#create_time-elt"] .= " 23:59:59";
//        }
        unset($requestMap["pageSize"]);
        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();
//        $requestMap["ho.enterprise_code"] = $user["enterprise_code"];
        $this->assign("begin_time", $_REQUEST["ho#create_date-egt"]);
        $this->assign("end_time", $_REQUEST["ho#create_date-elt"]);

        //分页
        $count = $this->currentModel->getListCount($requestMap);
        $pageSize = $_REQUEST["pageSize"];
        if(isNullOrEmpty($pageSize)){
            $pageSize = 50;
            $page = $this->page($count, $pageSize);
        }else{
            if($pageSize == -1){
                $page = $this->page($count, 0);
            }else{
                $page = $this->page($count, $pageSize);
            }
        }
        $this->assign('pageSize', $pageSize);

        //获取order列表
        if(isNullOrEmpty($requestMap["ho#status"])){
            $requestMap["ho#status-gt"] = '-3';
        }
        $orderList = $this->currentModel->queryForList($page, $requestMap);

        $totalCount = sizeof($orderList);

        $this->assign('totalCount', $totalCount);


        $this->assign("user", $user);
        $this->assign("defaultEnum", C("INVOICE_TYPE"));
        $this->assign("statusEnum", C("FINISHED_ORDER_STATUS"));
        $this->assign('orderList', $orderList);
        $this->assign("page", $page->show('Admin', $this->parameter));
        $this->display();

    }

    public function getHospitalOrderList() {

        $hospitalOrderId = I("post.hospitalOrderId");
        $hospitalOrder = D("HospitalOrder")->queryById($hospitalOrderId);
        $hospitalOperation = D("HospitalOperation")->queryById($hospitalOrder["hospital_operation_id"]);
        $idArr = explode(',', $hospitalOrder["product_list"]);
        $numArr = explode(',', $hospitalOrder["number_list"]);

        $allProductList = D('HospitalProduct')->select();
        $list =array();
//        $list["hospital_operation_name"] = $hospitalOrder["hospital_order_id"];
//        foreach ($allProductList as $product) {
//            $index = array_search($product["hospital_product_id"],$idArr);
//            if($index !== false){
//                $product["number"] = $numArr[$index];
//                array_push($list, $product);
//            }
//        }

        for($i = 0; $i < sizeof($idArr); $i++){
            foreach ($allProductList as $product) {
                if($idArr[$i] == $product["hospital_product_id"]){
                    $product["number"] = $numArr[$i];
                    array_push($list, $product);
                }
            }
        }

        echo json_encode($list);

    }

    public function outStock() {

        $hospitalOrderId = $_REQUEST["id"];
        $hospitalOrder = D("HospitalOrder")->queryById($hospitalOrderId);
        $hospitalOperation = D("HospitalOperation")->queryById($hospitalOrder["hospital_operation_id"]);
        $hospital = D("Hospital")->queryById($hospitalOperation["hospital_id"]);
        $sales = D("Admin")->where(array('employee_id'=>$hospitalOrder["employee_id"]))->find();
        $updater = D("Admin")->where(array('employee_id'=>$hospitalOrder["employee_id"]))->find();
        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();
        $this->assign("user", $user);
        $this->assign("hospitalOrder", $hospitalOrder);
        $this->assign("hospitalOperation", $hospitalOperation);
        $this->assign("hospital", $hospital);
        $this->assign("sales", $sales);
        $this->assign("updater", $updater);

        $productIdArr = explode(',', $hospitalOperation["product_list"]);

        $allProductList = D('HospitalProduct')->select();
        $list =array();

        $idArr = explode(',', $hospitalOrder["product_list"]);
        $numArr = explode(',', $hospitalOrder["number_list"]);

        foreach ($productIdArr as $productId) {
            foreach ($allProductList as $product) {
                if ($product["hospital_product_id"] == $productId){
                    $index = array_search($productId,$idArr);
                    if($index === false){
                        $product["number"] = 0;
                    }else{
                        $product["number"] = $numArr[$index];
                    }

                    array_push($list, $product);
                }
            }
        }
        $this->assign("list", $list);
        $this->assign("row", count($list));

        if($_REQUEST["closed"] == "yes"){
            $this->assign("closed", "yes");
        }

        $this->display();

    }

    public function outStockPost() {
        $hospitalOrderId = $_REQUEST["id"];
        $hospitalOrder = D("HospitalOrder")->queryById($hospitalOrderId);

        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();

        $hospitalOrder["update_id"] = $user["employee_id"];
        $hospitalOrder["update_time"] = getCurrentDate();
        $hospitalOrder["product_list"] = "";
        $hospitalOrder["number_list"] = "";
        $hospitalOrder["report_list"] = "";
        $row = $_REQUEST["row"];
        for($i = 0; $i < $row; $i++){
            if($_REQUEST["number_".$i] == 0){
                continue;
            }
            if(!isNullOrEmpty($hospitalOrder["product_list"])){
                $hospitalOrder["product_list"] .= ",";
                $hospitalOrder["number_list"] .=",";
                $hospitalOrder["report_list"] .= ",";
            }
            $hospitalOrder["product_list"] .= $_REQUEST["hospital_product_id_".$i];
            $hospitalOrder["number_list"] .= $_REQUEST["number_".$i];
            $hospitalOrder["report_list"] .= ($_REQUEST["hospital_product_name_".$i] . " x " . $_REQUEST["number_".$i]);
        }

        $hospitalOrder["number"] = $_REQUEST["hospital_order_number"];
        $hospitalOrder["create_date"] = $_REQUEST["create_date"];
        $hospitalOrder["op_date"] = $_REQUEST["op_date"];
        $hospitalOrder["doctor_name"] = $_REQUEST["doctor_name"];
        $hospitalOrder["patient_name"] = $_REQUEST["patient_name"];
        $hospitalOrder["note"] = $_REQUEST["note"];
        $hospitalOperation = D("HospitalOperation")->queryById($hospitalOrder["hospital_operation_id"]);
        $hospital = D("Hospital")->queryById($hospitalOperation["hospital_id"]);
        $creator = D("admin")->where(array('employee_id'=>$hospitalOrder["employee_id"]))->find();
        if(I('post.completed') == "on") {
            $hospitalOrder["status"] = 1;
            $hospitalOrder["delivery_id"] = $user["employee_id"];
            $hospitalOrder["outstock_time"] = getCurrentDate();
            //推送信息
            $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/hospitalProduct/hospitalOrderList/?id=". $hospitalOrderId;
            $notifyData["first"] = "手术订单已出库。医院：" . $hospital["hospital_name"];
            if($hospital["has_subhospital"] == 1)
                $notifyData["first"] .= "(" . $hospitalOrder["subhospital_name"] .")";
            $notifyData["keyword1"] = $hospitalOrder["patient_name"];
            $notifyData["keyword2"] = "医生：" . $hospitalOrder["doctor_name"] ."，手术日期 ".$hospitalOrder["op_date"];
            $notifyData["keyword3"] = $hospitalOrder["hospital_order_no"] ."，下单人：".$creator["admin_name"] ."，下单日期 ".$hospitalOrder["create_date"];
            $notifyData["keyword4"] = $hospitalOrder["outstock_time"] . "，出库人：".$user["admin_name"];
            $notifyData["keyword5"] = "[" . $hospitalOperation["hospital_operation_name"]."] 共 ".$hospitalOrder["number"]." 件";
            $notifyData["remark"] = $hospitalOrder["note"];

            $openidArray = getNotifyArrByName("createHospitalOrder", $user["enterprise_code"]);
            $creator = D("admin")->where(array('employee_id'=>$hospitalOrder["employee_id"]))->find();
            array_push($openidArray, $creator["openid"]);
            $openidArray = array_unique($openidArray);

            $exceptionOpenIdArray = getNotifyArrByName("exception", $user["enterprise_code"]);
            foreach ($openidArray as $openid) {
                if (in_array($openid, $exceptionOpenIdArray)) {
                    continue;
                }
                $notifyData["openid"] = $openid;
                hospitalOrderNotify($notifyData);
            }
            $text = "已标记手术订单：". $hospitalOperation["hospital_operation_name"] ."为已出库状态";
        }else if(I('post.closed') == "on") {
            $hospitalOrder["status"] = -3;
            $hospitalOrder["close_reason"] = $_REQUEST["close_reason"];
            $hospitalOrder["delivery_id"] = $user['employee_id'];
            $hospitalOrder["outstock_time"] = getCurrentDate();
            $creator = D("admin")->where(array('employee_id'=>$hospitalOrder["employee_id"]))->find();
            //推送信息
            $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/hospitalProduct/hospitalOrderList/?id=". $hospitalOrderId;
            $notifyData["first"] = "手术订单已关闭。医院：" . $hospital["hospital_name"];
            if($hospital["has_subhospital"] == 1)
                $notifyData["first"] .= "(" . $hospitalOrder["subhospital_name"] .")";
            $notifyData["keyword1"] = $hospitalOrder["patient_name"];
            $notifyData["keyword2"] = "医生：" . $hospitalOrder["doctor_name"] ."，手术日期 ".$hospitalOrder["op_date"];
            $notifyData["keyword3"] = $hospitalOrder["hospital_order_no"] ."，下单人：".$creator["admin_name"] ."，下单日期 ".$hospitalOrder["create_date"];
            $notifyData["keyword4"] = $hospitalOrder["update_time"] . "，关闭人：".$user["admin_name"];
            $notifyData["keyword5"] = "[" . $hospitalOperation["hospital_operation_name"]."] 共 ".$hospitalOrder["number"]." 件";
            $notifyData["remark"] = "关闭原因：".$hospitalOrder["close_reason"];

            $openidArray = getNotifyArrByName("createHospitalOrder", $user["enterprise_code"]);
            $creator = D("admin")->where(array('employee_id'=>$hospitalOrder["employee_id"]))->find();
            array_push($openidArray, $creator["openid"]);
            $openidArray = array_unique($openidArray);
            foreach ($openidArray as $openid) {
                $notifyData["openid"] = $openid;
                hospitalOrderNotify($notifyData);
            }

            $text = "已标记手术订单：". $hospitalOperation["hospital_operation_name"] ."为关闭状态";
        }
        else{
            $text = "已暂存手术订单：". $hospitalOperation["hospital_operation_name"] ."的内容";
        }

        D("HospitalOrder")->updateInfo($hospitalOrder);
        $this->success($text, U("hospitalOrder/index"));

    }

    public function closeOrder() {
        $hospitalOrderId = $_REQUEST["id"];
        $hospitalOrder = D("HospitalOrder")->queryById($hospitalOrderId);

        $hospitalOrder["status"] = -3;

        $users_obj= M("admin");
        $userId=$_SESSION['ADMIN_ID'];
        $user=$users_obj->where("user_id=$userId")->find();

        $hospitalOrder["delivery_id"] = $user['employee_id'];
        $hospitalOrder["outstock_time"] = getCurrentDate();
        D("HospitalOrder")->updateInfo($hospitalOrder);
        $creator = D("admin")->where(array('employee_id'=>$hospitalOrder["employee_id"]))->find();
        //推送信息
        $hospitalOperation = D("HospitalOperation")->queryById($hospitalOrder["hospital_operation_id"]);
        $hospital = D("Hospital")->queryById($hospitalOperation["hospital_id"]);
        $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/hospitalProduct/hospitalOrderList/?id=". $hospitalOrderId;
        $notifyData["first"] = "手术订单已关闭。医院：" . $hospital["hospital_name"];
        if($hospital["has_subhospital"] == 1)
            $notifyData["first"] .= "(" . $hospitalOrder["subhospital_name"] .")";
        $notifyData["keyword1"] = $hospitalOrder["patient_name"];
        $notifyData["keyword2"] = "医生：" . $hospitalOrder["doctor_name"] ."，手术日期 ".$hospitalOrder["op_date"];
        $notifyData["keyword3"] = $hospitalOrder["hospital_order_no"] ."，下单人：".$creator["admin_name"] ."，下单日期 ".$hospitalOrder["create_date"];
        $notifyData["keyword4"] = $hospitalOrder["update_time"];
        $notifyData["keyword5"] = "[" . $hospitalOperation["hospital_operation_name"]."] 共 ".$hospitalOrder["number"]." 件";
        $notifyData["remark"] = "关闭操作人：".$user["admin_name"]."，关闭时间：".$hospitalOrder["outstock_time"];

        $openidArray = getNotifyArrByName("createHospitalOrder", $user["enterprise_code"]);
        $creator = D("admin")->where(array('employee_id'=>$hospitalOrder["employee_id"]))->find();
        array_push($openidArray, $creator["openid"]);
        $openidArray = array_unique($openidArray);
        foreach ($openidArray as $openid) {
            $notifyData["openid"] = $openid;
            hospitalOrderNotify($notifyData);
        }
        $this->success("已标记手术订单：". $hospitalOperation["hospital_operation_name"] ."为已关闭状态", U("hospitalOrder/index"));
    }

    public function getTable()
    {
        $hospitalOrderId = $_REQUEST["id"];
        $hospitalOrder = D("HospitalOrder")->queryById($hospitalOrderId);
        $hospitalOperation = D("HospitalOperation")->queryById($hospitalOrder["hospital_operation_id"]);
        $hospital = D("Hospital")->queryById($hospitalOperation["hospital_id"]);

        $data = array();
        $data["header"] = array();
        $data["volume"] = array();
        $data["list"] = array();

        $data["header"] = [$hospitalOperation["hospital_operation_name"]];
        $data["volume"]= [0,1,2];
        array_push($data["list"], ["下单日期",$hospitalOrder["create_date"]]);
        array_push($data["list"], ["手术日期",$hospitalOrder["op_date"]]);
        if($hospital["has_subhospital"] == 1)
            array_push($data["list"], ["手术医院",$hospitalOrder["subhospital_name"]]);
        array_push($data["list"], ["手术医生",$hospitalOrder["doctor_name"]]);
        array_push($data["list"], ["病人姓名",$hospitalOrder["patient_name"]]);
        $creator = D("Admin")->where(array('employee_id'=>$hospitalOrder["employee_id"]))->find();
        array_push($data["list"], ["下单人",$creator["admin_name"]]);
        array_push($data["list"], "");
        array_push($data["list"], ["产品编号","产品描述","数量"]);

        $productIdArr = explode(',', $hospitalOrder["product_list"]);
        $numberArr = explode(',', $hospitalOrder["number_list"]);
        foreach ($productIdArr as $key => $value){
            $product = D('HospitalProduct')->where(array('hospital_product_id' => $value))->find();
            array_push($data["list"], [$product["code"], $product["hospital_product_name"], $numberArr[$key]]);
        }

//        $users_obj= M("admin");
//        $userId=$_SESSION['ADMIN_ID'];
//        $user=$users_obj->where("user_id=$userId")->find();

//        $fileName = "医院订单_" . $hospital["hospital_name"] . "_" . date('Ymd',time()) . $hospitalOrderId;
        $fileName = $hospital["hospital_name"] . "_" . mb_substr($hospitalOperation["hospital_operation_name"],0,6,'utf-8') ."_"  . $hospitalOrder["number"] ."件_". mb_substr($hospitalOrder["patient_name"], 0 ,4,'utf-8') . $hospitalOrderId;


        $data["bold"] = "1,2,3,4,5,6,8";
        if( $hospitalOrder["status"] != 1){
            $data["header"] = [$hospitalOperation["hospital_operation_name"], "未出库"];
            $data["red"] = "1";
            $fileName .= "_未出库";
        }

        exportExcel($data, $fileName);
    }

}